'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Tooltip as UITooltip } from '@/components/ui/tooltip'
import { Progress } from '@/components/ui/progress'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import { createClient } from '@/lib/supabase/client'
import { Database } from '@/lib/supabase/types'
import { CheckCircle2, Calendar, ArrowUpRight, Clock } from 'lucide-react'
import { format } from 'date-fns'

// 定义类型
type Goal = Database['public']['Tables']['therapeutic_goals']['Row']

export interface ProgressSummaryProps {
  userId: string
}

export function ProgressSummary({ userId }: ProgressSummaryProps) {
  const [goals, setGoals] = useState<Goal[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const supabase = createClient()

  // 获取目标数据
  useEffect(() => {
    const fetchGoals = async () => {
      try {
        setLoading(true)
        // 在实际应用中，这里应该从数据库获取用户的目标数据
        // 此处为演示，使用模拟数据
        const mockGoals: Goal[] = [
          {
            id: '1',
            user_id: userId,
            goal_title: '管理焦虑情绪',
            goal_description: '学习识别焦虑触发因素并应用应对策略',
            goal_category: 'emotional',
            target_completion_date: '2023-12-31',
            current_progress: 65,
            success_metrics: { '焦虑发作频率': '减少50%', '应对策略使用率': '80%' },
            status: 'active',
            created_at: '2023-06-01T12:00:00Z',
            updated_at: '2023-09-15T12:00:00Z'
          },
          {
            id: '2',
            user_id: userId,
            goal_title: '改善睡眠质量',
            goal_description: '建立规律的睡眠习惯，减少夜间醒来次数',
            goal_category: 'other',
            target_completion_date: '2023-11-30',
            current_progress: 40,
            success_metrics: { '睡眠时间': '7小时/晚', '睡眠质量评分': '7/10' },
            status: 'active',
            created_at: '2023-07-15T12:00:00Z',
            updated_at: '2023-09-15T12:00:00Z'
          },
          {
            id: '3',
            user_id: userId,
            goal_title: '增强自信心',
            goal_description: '通过每日积极肯定和挑战消极思维来提高自尊',
            goal_category: 'self_esteem',
            target_completion_date: '2024-01-31',
            current_progress: 30,
            success_metrics: { '自我肯定实践': '每天2次', '消极思维识别率': '60%' },
            status: 'active',
            created_at: '2023-08-10T12:00:00Z',
            updated_at: '2023-09-15T12:00:00Z'
          }
        ]

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        setGoals(mockGoals)
      } catch (error) {
        console.error('Error fetching goals:', error)
        setError('获取目标数据失败')
      } finally {
        setLoading(false)
      }
    }

    fetchGoals()
  }, [userId])

  // 计算总体进度
  const overallProgress = goals.length > 0
    ? Math.round(goals.reduce((sum, goal) => sum + goal.current_progress, 0) / goals.length)
    : 0

  // 准备图表数据
  const chartData = goals.map(goal => ({
    name: goal.goal_title.substring(0, 10) + '...',
    progress: goal.current_progress
  }))

  // 目标类别映射
  const goalCategories: Record<string, string> = {
    'emotional': '情绪管理',
    'relationship': '人际关系',
    'self_esteem': '自尊自信',
    'coping': '应对策略',
    'other': '其他'
  }

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Progress Summary</CardTitle>
          <CardDescription>
            Your therapeutic journey progress
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-8">
            <div className="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-blue-500"></div>
          </div>
        </CardContent>
      </Card>
    )
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Progress Summary</CardTitle>
          <CardDescription>
            Your therapeutic journey progress
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="text-center py-8 text-red-500">
            <div className="text-lg font-medium">{error}</div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Progress Summary</CardTitle>
        <CardDescription>
          Your therapeutic journey progress
        </CardDescription>
      </CardHeader>
      <CardContent>
        {goals.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <div className="text-lg font-medium">You haven't set any goals yet</div>
            <div className="text-sm mt-2">Set your first goal to track your progress</div>
          </div>
        ) : (
          <div className="space-y-6">
            {/* 总体进度 */}
            <div>
              <div className="flex justify-between mb-2">
                <span className="text-sm font-medium text-gray-700">Overall Progress</span>
                <span className="text-sm font-medium text-gray-700">{overallProgress}%</span>
              </div>
              <Progress value={overallProgress} className="h-2" />
            </div>

            {/* 进度图表 */}
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={chartData}
                  margin={{ top: 5, right: 5, left: 5, bottom: 5 }}
                >
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="name" tick={{ fontSize: 12 }} />
                  <YAxis domain={[0, 100]} tick={{ fontSize: 12 }} />
                  <Tooltip />
                  <Bar dataKey="progress" fill="#86EFAC" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </div>

            {/* 最近目标活动 */}
            <div>
              <h3 className="text-sm font-medium text-gray-900 mb-3">Recent Goal Activities</h3>
              <div className="space-y-3">
                {goals.slice(0, 2).map((goal) => (
                  <div key={goal.id} className="flex items-start space-x-3 p-3 bg-gray-50 rounded-lg">
                    <div className="flex-shrink-0">
                      <div className="h-8 w-8 rounded-full bg-green-100 flex items-center justify-center">
                        <ArrowUpRight className="h-4 w-4 text-green-600" />
                      </div>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {goal.goal_title}
                      </p>
                      <p className="text-xs text-gray-500 mt-1">
                        {goalCategories[goal.goal_category] || goal.goal_category} • {goal.current_progress}% complete
                      </p>
                    </div>
                    <div className="flex-shrink-0 flex items-center space-x-1 text-xs text-gray-500">
                      <Clock className="h-3 w-3" />
                      <span>{format(new Date(goal.updated_at), 'MMM d')}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* 即将到期的目标 */}
            <div>
              <h3 className="text-sm font-medium text-gray-900 mb-3">Upcoming Deadlines</h3>
              <div className="space-y-3">
                {goals
                  .filter(goal => goal.target_completion_date && new Date(goal.target_completion_date) > new Date())
                  .sort((a, b) => new Date(a.target_completion_date!).getTime() - new Date(b.target_completion_date!).getTime())
                  .slice(0, 2)
                  .map((goal) => (
                    <div key={goal.id} className="flex items-start space-x-3 p-3 bg-gray-50 rounded-lg">
                      <div className="flex-shrink-0">
                        <div className="h-8 w-8 rounded-full bg-blue-100 flex items-center justify-center">
                          <Calendar className="h-4 w-4 text-blue-600" />
                        </div>
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-900 truncate">
                          {goal.goal_title}
                        </p>
                        <p className="text-xs text-gray-500 mt-1">
                          Due on {format(new Date(goal.target_completion_date!), 'MMM d, yyyy')}
                        </p>
                      </div>
                      <UITooltip content="View details">
                        <div className="flex-shrink-0 h-8 w-8 rounded-full bg-gray-100 flex items-center justify-center cursor-pointer hover:bg-gray-200 transition-colors">
                          <CheckCircle2 className="h-4 w-4 text-gray-600" />
                        </div>
                      </UITooltip>
                    </div>
                  ))}
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  )
}